package gazzera.node.core;

import gazzera.utils.*;

import java.io.*;
import java.util.*;

public class Config
{
	private static final String CONF = "conf";
	private Properties properties = new Properties();
	private File dir;

	public Config(String hash) throws Exception
	{
		dir = new File("database"+File.separator+hash);
	    dir.mkdirs();
	    File props = new File(dir, CONF);
	    if(props.exists())
	    {
			InputStream is = new FileInputStream(props);
			properties.load(is);
			is.close();
	    }
	    else
	    {
	    	String nickname = Str.strip(System.getProperty("user.name")).trim();
	    	properties.put("nickname", nickname.equals("")?"StrangeNickname":nickname);
	    	properties.put("core.port", ""+(new Random(System.currentTimeMillis()).nextInt(5000)+5000));
	    	properties.put("share.1.folder", new File(dir, "completed").toString());
	    	OutputStream is = new FileOutputStream(props);
			properties.store(is, "");
			is.close();
	    }
	}
	public void save() throws IOException
	{
		File props = new File(dir, CONF);
		OutputStream is = new FileOutputStream(props);
		try
		{
			properties.store(is, "");
		}
		finally
		{
			is.close();
		}
		
	}
	public void set(String name, String value)
	{
		if(Str.isEmpty(value))
		{
			properties.remove(name);
		}
		else
		{
			properties.setProperty(name, value);
		}
	}
	public Set<Object> keys()
	{	
		return properties.keySet();
	}
	public String get(String name, String defaultValue)
	{
		return properties.getProperty(name, defaultValue);
	}
	public String get(String name)
	{
		return properties.getProperty(name);
	}
	public File getMainFolder()
	{
		return dir;
	}
	
}
